import axios from 'axios'

import router from '@/router'

const service = axios.create({
  baseURL: 'http://localhost:8081', // 注意这里去掉了/api
  timeout: 10000,
  withCredentials: true // 关键：允许携带cookie和认证头
})

// 请求拦截器
service.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}` // 确保Token格式正确
    config.headers['Content-Type'] = 'application/json' // 明确指定Content-Type
  }
  return config
}, error => {
  return Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(response => {
  return response.data // 直接返回后端原始数据
}, error => {
  if (error.response?.status === 401) {
    router.push('/login')
  }
  return Promise.reject(error)
})

export default service
